package net.wanho.customerManage.service.impl;

import com.github.pagehelper.PageInfo;
import net.wanho.commons.exception.DaoException;
import net.wanho.commons.exception.ServiceException;
import net.wanho.commons.factory.BeanFactory;
import net.wanho.customerManage.dao.AdvancedLogDao;
import net.wanho.customerManage.dao.BusinessDao;
import net.wanho.customerManage.dao.BusinessSourceDao;
import net.wanho.customerManage.dto.AdvancedLogDto;
import net.wanho.customerManage.po.AdvancedLog;
import net.wanho.customerManage.po.Business;
import net.wanho.customerManage.query.BusinessQuery;
import net.wanho.customerManage.service.BusinessService;
import net.wanho.customerManage.vo.BusinessVo;
import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

public class BusinessServiceImpl implements BusinessService {
    private BusinessDao businessDao = BeanFactory.getBean(BusinessDao.class) ;
    private AdvancedLogDao advancedLogDao = BeanFactory.getBean(AdvancedLogDao.class) ;
    @Override
    public PageInfo<BusinessVo> selectCurrPage(int pageNum, int pageSize, BusinessQuery businessQuery) throws ServiceException {
        try {
            PageInfo<BusinessVo> businessVoPageInfo = new PageInfo<>();
            businessVoPageInfo.setPageNum(pageNum);
            businessVoPageInfo.setPageSize(pageSize);
            long total = businessDao.selectTotalByCondBusiness(businessQuery);
            List<BusinessVo> businessVoList = businessDao.selectCurrPageByCondBusiness(pageNum, pageSize, businessQuery);
            businessVoPageInfo.setPages((int) ((total+pageSize-1)/pageSize));
            businessVoPageInfo.setTotal(total);
            businessVoPageInfo.setList(businessVoList);
            return businessVoPageInfo ;
        } catch (DaoException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage()) ;
        }
    }

    @Override
    public Integer insertAdvancedLog(AdvancedLogDto advancedLogDto) throws ServiceException {
        try {
            //1. 根据商机id 进行查询
            Business business = businessDao.selectByIdBusiness(advancedLogDto.getBusinessId());
            //2. 新增推进日志
            AdvancedLog advancedLog = new AdvancedLog();
            BeanUtils.copyProperties(advancedLog,advancedLogDto);
            advancedLog.setCreateTime(new Date());
            advancedLogDao.insertAdvancedLog(advancedLog) ;
            //3. 修改 商机
            BeanUtils.copyProperties(business,advancedLogDto);
            business.setUpdateTime(new Date());
            businessDao.updateBusiness(business);
            return 1;
        } catch (DaoException |IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage()) ;
        }
    }
}
